package com.qiantu.phone.ui.activity;

import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.bigkoo.pickerview.adapter.NumericWheelAdapter;
import com.contrarywind.view.WheelView;
import com.contrarywind.listener.OnItemSelectedListener;
import com.hjq.base.BaseAdapter;
import com.hjq.base.BaseDialog;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.widget.layout.SettingBar;
import com.hjq.widget.view.SwitchButton;
import com.lxj.xpopup.XPopup;
import com.qiantu.api.entity.LinkageBean;
import com.qiantu.phone.R;
import com.qiantu.phone.app.AppActivity;
import com.qiantu.phone.app.AppApplication;
import com.qiantu.phone.ui.adapter.ListLabelAdapter;
import com.qiantu.phone.ui.dialog.BottomDelayTimeDialog;
import com.qiantu.phone.ui.dialog.BottomListDialog;
import com.qiantu.phone.ui.dialog.BottomTimePeriodDialog;
import com.qiantu.phone.ui.uiutil.LLSceneLinkageUtil;
import com.qiantu.phone.utils.LinkageDataHolder;
import com.qiantu.phone.utils.TempDataHolder;
import com.qiantu.phone.ui.dialog.ConfirmHintDialog;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

public class EditTimeActivity extends AppActivity {
    private SettingBar timeTypeSetting;
    private SwitchButton btnSwitch;
    private SwitchButton btnReverseSwitch;
    private View selectDayLayout;
    private WheelView wheelView1;
    private WheelView wheelView2;
    private View btnMonday;
    private View btnTuesday;
    private View btnWednesday;
    private View btnThursday;
    private View btnFriday;
    private View btnSaturday;
    private View btnSunday;
    private String serialNo;
    private LinkageBean mLinkageBean;
    private LinkageBean.LinkageCondition mLinkageCondition;
    private WheelView wv_first;
    private WheelView wv_second;
    private WheelView wv_third;
    private WheelView wv_four;
    private NumericWheelAdapter mFirstNumericWheelAdapter;
    private NumericWheelAdapter mSecondNumericWheelAdapter;
    private NumericWheelAdapter mThirdNumericWheelAdapter;
    private NumericWheelAdapter mFourNumericWheelAdapter;
    private ShapeLinearLayout timeLayout;
    private ShapeLinearLayout timeSlotLayout;
    private ShapeLinearLayout sunriseSunsetLayout;
    private BottomListDialog mBottomActionDialog;
    private TextView sunriseSunsetLeft;
    private TextView sunriseSunsetRight;
    private WheelView sunriseSunsetOffset;
    private WheelView sunriseSunsetOffsetTo;
    private int leftSunType = 0;  // 0=日出, 1=日落
    private int rightSunType = 1; // 0=日出, 1=日落
    private static final String[] SUN_TYPES = {"日出", "日落"};
    private static final int[] OFFSET_VALUES = {-120, -60, -30, -10, -5, 0, 5, 10, 30, 60, 120};
    private static final String[] OFFSET_LABELS = {
        "前5分钟", "前10分钟", "前30分钟", "前1小时", "前2小时", "",
        "后5分钟", "后10分钟", "后30分钟", "后1小时", "后2小时"
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_edit_time;
    }

    @Override
    protected void initView() {
        timeTypeSetting = findViewById(R.id.setting_time_type);
        btnSwitch = findViewById(R.id.btn_switch);
        btnReverseSwitch = findViewById(R.id.btn_reverse_switch);
        selectDayLayout = findViewById(R.id.select_day_layout);
        wheelView1 = findViewById(R.id.wheel_view1);
        wheelView2 = findViewById(R.id.wheel_view2);
        btnMonday = findViewById(R.id.btn_monday);
        btnTuesday = findViewById(R.id.btn_tuesday);
        btnWednesday = findViewById(R.id.btn_wednesday);
        btnThursday = findViewById(R.id.btn_thursday);
        btnFriday = findViewById(R.id.btn_friday);
        btnSaturday = findViewById(R.id.btn_saturday);
        btnSunday = findViewById(R.id.btn_sunday);
        wv_first = findViewById(R.id.options1);
        wv_second = findViewById(R.id.options2);
        wv_third = findViewById(R.id.options3);
        wv_four = findViewById(R.id.options4);
        timeLayout = findViewById(R.id.time_container);
        timeSlotLayout = findViewById(R.id.time_slot_container);
        sunriseSunsetLayout = findViewById(R.id.sunrise_sunset_container);
        sunriseSunsetLeft = findViewById(R.id.sunrise_sunset_left);
        sunriseSunsetRight = findViewById(R.id.sunrise_sunset_right);
        sunriseSunsetOffset = findViewById(R.id.sunrise_sunset_offset);
        sunriseSunsetOffsetTo = findViewById(R.id.sunrise_sunset_offsetTo);
        setOnClickListener(timeTypeSetting,btnMonday, btnTuesday, btnWednesday, btnThursday, btnFriday, btnSaturday, btnSunday);
        btnSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    selectDayLayout.setVisibility(View.VISIBLE);
                }else{
                    selectDayLayout.setVisibility(View.GONE);
                }
            }
        });
        initWheelView();
        sunriseSunsetLeft.setOnClickListener(v -> showSunTypeDialog(true));
        sunriseSunsetRight.setOnClickListener(v -> showSunTypeDialog(false));
        sunriseSunsetOffset.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[leftSunType])));
        sunriseSunsetOffsetTo.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[rightSunType])));
        sunriseSunsetOffset.setCurrentItem(5);
        sunriseSunsetOffsetTo.setCurrentItem(5);
        sunriseSunsetOffset.setCyclic(false);
        sunriseSunsetOffsetTo.setCyclic(false);
    }

    private void initWheelView() {
        wheelView1.setGravity(Gravity.CENTER);
        wheelView1.setCyclic(true);
        wheelView1.setAlphaGradient(true);
        wheelView1.setItemsVisibleCount(5);
        wheelView1.setDividerColor(0x00000000);
        wheelView1.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wheelView1.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wheelView2.setGravity(Gravity.CENTER);
        wheelView2.setCyclic(true);
        wheelView2.setAlphaGradient(true);
        wheelView2.setItemsVisibleCount(5);
        wheelView2.setDividerColor(0x00000000);
        wheelView2.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wheelView2.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_first.setGravity(Gravity.CENTER);
        wv_first.setCyclic(true);
        wv_first.setAlphaGradient(true);
        wv_first.setItemsVisibleCount(5);
        wv_first.setDividerColor(0x00000000);
        wv_first.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_first.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_second.setGravity(Gravity.CENTER);
        wv_second.setCyclic(true);
        wv_second.setAlphaGradient(true);
        wv_second.setItemsVisibleCount(5);
        wv_second.setDividerColor(0x00000000);
        wv_second.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_second.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_third.setGravity(Gravity.CENTER);
        wv_third.setCyclic(true);
        wv_third.setAlphaGradient(true);
        wv_third.setItemsVisibleCount(5);
        wv_third.setDividerColor(0x00000000);
        wv_third.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_third.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wv_four.setGravity(Gravity.CENTER);
        wv_four.setCyclic(true);
        wv_four.setAlphaGradient(true);
        wv_four.setItemsVisibleCount(5);
        wv_four.setDividerColor(0x00000000);
        wv_four.setTextColorCenter(AppApplication.getInstance().getThemeColor(R.attr.themeColor));
        wv_four.setTextSize(getResources().getDimensionPixelSize(R.dimen.dp_18));

        wheelView1.setAdapter(new NumericWheelAdapter(0, 23));
        wheelView1.setCurrentItem(0);

        wheelView2.setAdapter(new NumericWheelAdapter(0, 59));
        wheelView2.setCurrentItem(0);

        mFirstNumericWheelAdapter  = new NumericWheelAdapter(0, 23);
        wv_first.setAdapter(mFirstNumericWheelAdapter);
        wv_first.setCurrentItem(0);

        mSecondNumericWheelAdapter  = new NumericWheelAdapter(0, 59);
        wv_second.setAdapter(mSecondNumericWheelAdapter);
        wv_second.setCurrentItem(0);

        mThirdNumericWheelAdapter  = new NumericWheelAdapter(0, 23);
        wv_third.setAdapter(mThirdNumericWheelAdapter);
        wv_third.setCurrentItem(0);

        mFourNumericWheelAdapter  = new NumericWheelAdapter(0, 59);
        wv_four.setAdapter(mFourNumericWheelAdapter);
        wv_four.setCurrentItem(0);
    }

    @Override
    protected void initData() {
        serialNo = getString("serial_no");
        mLinkageBean = LinkageDataHolder.getLinkageData();
        if(mLinkageBean != null){
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if(linkageConditions != null && linkageConditions.size() > 0 && !TextUtils.isEmpty(serialNo)){
                for(LinkageBean.LinkageCondition item : linkageConditions){
                    if(item.getConditionSerialNo().equals(serialNo)){
                        mLinkageCondition = item;
                        updateView();
                        break;
                    }
                }
            }
        }
        if(mLinkageCondition == null){
            if(mLinkageBean == null){
                mLinkageBean = new LinkageBean();
                LinkageDataHolder.setLinkageData(mLinkageBean);
            }
            List<LinkageBean.LinkageCondition> linkageConditions = mLinkageBean.getLinkageConditions();
            if(linkageConditions == null){
                linkageConditions = new ArrayList<>();
            }
            mLinkageBean.setLinkageConditions(linkageConditions);
            mLinkageCondition = new LinkageBean.LinkageCondition();
            mLinkageCondition.setConditionSerialNo(UUID.randomUUID().toString());
            mLinkageCondition.setConditionType(1);
            mLinkageCondition.setTimingType(1);
            mLinkageCondition.setMonday(true);
            mLinkageCondition.setTuesday(true);
            mLinkageCondition.setWednesday(true);
            mLinkageCondition.setThursday(true);
            mLinkageCondition.setFriday(true);
            mLinkageCondition.setSaturday(true);
            mLinkageCondition.setSunday(true);
            mLinkageCondition.setToSunTypeId(1);
            mLinkageCondition.setMinute(0);
            mLinkageCondition.setToMinute(0);
            linkageConditions.add(mLinkageCondition);
            mLinkageCondition.setSort(linkageConditions.indexOf(mLinkageCondition) + 1);
            updateView();
        }
    }

    private void updateView() {
        if(mLinkageCondition.getTimeTypeId() == 0){
            timeLayout.setVisibility(View.VISIBLE);
            timeSlotLayout.setVisibility(View.GONE);
            sunriseSunsetLayout.setVisibility(View.GONE);
            timeTypeSetting.setRightText("时间点");
        }else if(mLinkageCondition.getTimeTypeId() == 1){
            timeLayout.setVisibility(View.GONE);
            timeSlotLayout.setVisibility(View.VISIBLE);
            sunriseSunsetLayout.setVisibility(View.GONE);
            timeTypeSetting.setRightText("时间段");
        }else if(mLinkageCondition.getTimeTypeId() == 2){
            timeLayout.setVisibility(View.GONE);
            timeSlotLayout.setVisibility(View.GONE);
            sunriseSunsetLayout.setVisibility(View.VISIBLE);
            timeTypeSetting.setRightText("日出日落");
            sunriseSunsetLeft.setText(SUN_TYPES[mLinkageCondition.getSunTypeId()]);
            sunriseSunsetRight.setText(SUN_TYPES[mLinkageCondition.getToSunTypeId()]);
            leftSunType = mLinkageCondition.getSunTypeId();
            rightSunType = mLinkageCondition.getToSunTypeId();
            sunriseSunsetOffset.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[leftSunType])));
            sunriseSunsetOffsetTo.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[rightSunType])));
            sunriseSunsetOffset.setCurrentItem(getOffsetIndex(mLinkageCondition.getMinute()));
            sunriseSunsetOffsetTo.setCurrentItem(getOffsetIndex(mLinkageCondition.getToMinute()));
            sunriseSunsetOffset.setCyclic(false);
            sunriseSunsetOffsetTo.setCyclic(false);
        }
        
        wheelView1.setCurrentItem(mLinkageCondition.getHour());
        wheelView2.setCurrentItem(mLinkageCondition.getMinute());
        wv_first.setCurrentItem(mLinkageCondition.getHour());
        wv_second.setCurrentItem(mLinkageCondition.getMinute());
        wv_third.setCurrentItem(mLinkageCondition.getToHour());
        wv_four.setCurrentItem(mLinkageCondition.getToMinute());
        btnSwitch.setChecked(mLinkageCondition.getTimingType() == 1);
        btnMonday.setSelected(mLinkageCondition.isMonday());
        btnTuesday.setSelected(mLinkageCondition.isTuesday());
        btnWednesday.setSelected(mLinkageCondition.isWednesday());
        btnThursday.setSelected(mLinkageCondition.isThursday());
        btnFriday.setSelected(mLinkageCondition.isFriday());
        btnSaturday.setSelected(mLinkageCondition.isSaturday());
        btnSunday.setSelected(mLinkageCondition.isSunday());
    }

    private int getTimeOffsetIndex(int minutes) {
        for (int i = 0; i < OFFSET_VALUES.length; i++) {
            if (OFFSET_VALUES[i] == minutes) return i;
        }
        return 0; // 默认选中"日出"或"日落"本身（0分钟）
    }

    private int getMinutesFromOffset(int offset) {
        if (offset >= 0 && offset < OFFSET_VALUES.length) {
            return OFFSET_VALUES[offset];
        }
        return 0;
    }

    private int getOffsetIndex(int minute) {
        for (int i = 0; i < OFFSET_VALUES.length; i++) {
            if (OFFSET_VALUES[i] == minute) return i;
        }
        return 5; // 默认选中"日出"或"日落"本身（0分钟）
    }

    @Override
    public void onRightClick(View view) {
        if(btnSwitch.isChecked()
                && !btnMonday.isSelected()
                && !btnTuesday.isSelected()
                && !btnWednesday.isSelected()
                && !btnThursday.isSelected()
                && !btnFriday.isSelected()
                && !btnSaturday.isSelected()
                && !btnSunday.isSelected()){
            toast(R.string.please_select_repeat_day_hint);
            return;
        }
        if(mLinkageCondition.getTimeTypeId() == 0){
            mLinkageCondition.setHour(wheelView1.getCurrentItem());
            mLinkageCondition.setMinute(wheelView2.getCurrentItem());
        }else if(mLinkageCondition.getTimeTypeId() == 1){
            mLinkageCondition.setHour(wv_first.getCurrentItem());
            mLinkageCondition.setMinute(wv_second.getCurrentItem());
            mLinkageCondition.setToHour(wv_third.getCurrentItem());
            mLinkageCondition.setToMinute(wv_four.getCurrentItem());
        }else if(mLinkageCondition.getTimeTypeId() == 2){
            mLinkageCondition.setSunTypeId(leftSunType);
            mLinkageCondition.setToSunTypeId(rightSunType);
            mLinkageCondition.setMinute(OFFSET_VALUES[sunriseSunsetOffset.getCurrentItem()]);
            mLinkageCondition.setToMinute(OFFSET_VALUES[sunriseSunsetOffsetTo.getCurrentItem()]);
        }
        mLinkageCondition.setMonday(btnSwitch.isChecked() && btnMonday.isSelected());
        mLinkageCondition.setTuesday(btnSwitch.isChecked() && btnTuesday.isSelected());
        mLinkageCondition.setWednesday(btnSwitch.isChecked() && btnWednesday.isSelected());
        mLinkageCondition.setThursday(btnSwitch.isChecked() && btnThursday.isSelected());
        mLinkageCondition.setFriday(btnSwitch.isChecked() && btnFriday.isSelected());
        mLinkageCondition.setSaturday(btnSwitch.isChecked() && btnSaturday.isSelected());
        mLinkageCondition.setSunday(btnSwitch.isChecked() && btnSunday.isSelected());
        mLinkageCondition.setImageUrl("icon_intelligent_condition_timing");
        mLinkageCondition.setBriefing("timing");
        mLinkageCondition.setTimingType(btnSwitch.isChecked() ? 1 : 0);
        mLinkageCondition.setReverse(btnReverseSwitch.isChecked());
        startActivity_SingleTask(EditLinkageActivity.class);
        finish();
    }

    private void showBottomListDialog() {
        if (mBottomActionDialog == null) {
            mBottomActionDialog = new BottomListDialog(this);
            mBottomActionDialog.setDialogClickListener(new BottomListDialog.DialogClickListener() {
                @Override
                public void onConfirmClick() {

                }
            });
            ListLabelAdapter listLabelAdapter = new ListLabelAdapter(this);
            List<String> data = new ArrayList<>();
            data.add("时间点");
            data.add("固定时间段");
            data.add("日出日落时间段");
            listLabelAdapter.setData(data);
            listLabelAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(RecyclerView recyclerView, View itemView, int position) {
                    mLinkageCondition.setTimeTypeId(position);
                    if(mLinkageCondition.getTimeTypeId() == 0){
                        timeLayout.setVisibility(View.VISIBLE);
                        timeSlotLayout.setVisibility(View.GONE);
                        sunriseSunsetLayout.setVisibility(View.GONE);
                        timeTypeSetting.setRightText("时间点");
                    }else if(mLinkageCondition.getTimeTypeId() == 1){
                        timeLayout.setVisibility(View.GONE);
                        timeSlotLayout.setVisibility(View.VISIBLE);
                        sunriseSunsetLayout.setVisibility(View.GONE);
                        timeTypeSetting.setRightText("固定时间段");
                    }else if(mLinkageCondition.getTimeTypeId() == 2){
                        timeLayout.setVisibility(View.GONE);
                        timeSlotLayout.setVisibility(View.GONE);
                        sunriseSunsetLayout.setVisibility(View.VISIBLE);
                        timeTypeSetting.setRightText("日出日落时间段");
                    }
                    mBottomActionDialog.dismiss();
                }
            });
            mBottomActionDialog.setAdapter(listLabelAdapter);
            new XPopup.Builder(this)
                    .dismissOnBackPressed(true)
                    .enableDrag(true)
                    .asCustom(mBottomActionDialog);
        }
        ListLabelAdapter listLabelAdapter = (ListLabelAdapter) mBottomActionDialog.getAdapter();
        listLabelAdapter.setSelected("");
        mBottomActionDialog.show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.setting_time_type:
                showBottomListDialog();
                break;
            default:
                view.setSelected(!view.isSelected());
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if (mLinkageCondition != null && !TextUtils.isEmpty(serialNo)) {
            finish();
        } else {
            new ConfirmHintDialog.Builder(this)
                .setContent(getString(R.string.edit_back_hint))
                .setLeftBtnText(getString(R.string.cancel))
                .setRightBtnText(getString(R.string.back))
                .setLeftBtnStrongHint(true)
                .setListener(new ConfirmHintDialog.OnListener() {
                    @Override
                    public void onLeftClick(BaseDialog dialog) {
                        dialog.dismiss();
                    }

                    @Override
                    public void onConfirm(BaseDialog dialog) {
                        dialog.dismiss();
                        if (mLinkageBean != null && mLinkageCondition != null) {
                            mLinkageBean.getLinkageConditions().remove(mLinkageCondition);
                        }
                        finish();
                    }
                })
                .show();
        }
    }

    private List<String> getSunTypeOffsetOptions(String sunType) {
        List<String> list = new ArrayList<>();
        for (String label : OFFSET_LABELS) {
            if ("".equals(label)) {
                list.add(sunType);
            } else {
                list.add(sunType + label);
            }
        }
        return list;
    }

    private void showSunTypeDialog(boolean isLeft) {
        List<String> options = Arrays.asList(SUN_TYPES);
        new XPopup.Builder(this)
            .asBottomList("选择", options.toArray(new String[0]), (pos, text) -> {
                if (isLeft) {
                    leftSunType = pos;
                    sunriseSunsetLeft.setText(SUN_TYPES[pos]);
                    sunriseSunsetOffset.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[pos])));
                    sunriseSunsetOffset.setCurrentItem(5);
                    sunriseSunsetOffset.setCyclic(false);
                } else {
                    rightSunType = pos;
                    sunriseSunsetRight.setText(SUN_TYPES[pos]);
                    sunriseSunsetOffsetTo.setAdapter(new ArrayWheelAdapter<>(getSunTypeOffsetOptions(SUN_TYPES[pos])));
                    sunriseSunsetOffsetTo.setCurrentItem(5);
                    sunriseSunsetOffsetTo.setCyclic(false);
                }
            }).show();
    }
}